﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using T.ApiResults;
using T.Personnel.Domain;
using T.Personnel.Domain.Dto;
using T.Personnel.Read.API.Application.Command.RegisterCommand;

namespace T.Personnel.Read.API.Controllers
{
    /// <summary>
    /// 人事管理-员工登记-读
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class ReadRegisterController : ControllerBase
    {
        private readonly IMediator mediator;

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="mediator"></param>
        public ReadRegisterController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 获取员工列表
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<Result<Register>>> GetListRegisterAsync([FromQuery]GetListRegisterCommand command)
        {
            ApiResult<Result<Register>> result = new ApiResult<Result<Register>>();
            try
            {
                result.Data = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;

                throw;
            }
        }

        /// <summary>
        /// 获取员工反填
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<Register>> GetRegisterAsync([FromQuery]GetRegisterCommand command)
        {
            ApiResult<Register> result = new ApiResult<Register>();
            try
            {
                result.Data = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
                throw;
            }
        }

        /// <summary>
        /// 入职获取员工信息
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<ItemsDto>>> GetUserEntryAsync([FromQuery]GetUserEntryCommand command)
        {
            ApiResult<List<ItemsDto>> result = new ApiResult<List<ItemsDto>>();
            try
            {
                result.Data = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
                throw;
            }
        }

        /// <summary>
        /// 转正获取员工信息
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<ItemsDto>>> GetUserFullAsync([FromQuery] GetUserFullCommand command)
        {
            ApiResult<List<ItemsDto>> result = new ApiResult<List<ItemsDto>>();
            try
            {
                result.Data = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
                throw;
            }
        }

        /// <summary>
        /// 离职获取员工信息
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<ItemsDto>>> GetUserResignationAsync([FromQuery] GetUserResignationCommand command)
        {
            ApiResult<List<ItemsDto>> result = new ApiResult<List<ItemsDto>>();
            try
            {
                result.Data = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
                throw;
            }
        }

        /// <summary>
        /// 获取上级员工信息
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<ItemsDto>>> GetPrincipalsAsync([FromQuery] GetPrincipalsCommand command)
        {
            ApiResult<List<ItemsDto>> result = new ApiResult<List<ItemsDto>>();
            try
            {
                result.Data = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
                throw;
            }
        }

        /// <summary>
        /// 计算员工年龄比
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<AgeGroupDto>> AgeGroupAsync([FromQuery]AgeGroupCommand command)
        {
            var gather = await mediator.Send(command);
            gather = gather.Where(x => x.State == "试用期" || x.State == "待转正" || x.State == "已转正" || x.State == "待离职").ToList();
            var currentDate = DateTime.Now;  // 当前日期
            var ageGroups = gather.Select(r => new
            {
                Age = r.Birthday.HasValue
                        ? currentDate.Year - r.Birthday.Value.Year -
                          (currentDate < r.Birthday.Value.AddYears(currentDate.Year - r.Birthday.Value.Year) ? 1 : 0)
                        : 0,  // 如果 Birthday 是 null，则默认年龄为 0
                r.Id
            })
                .GroupBy(r =>
                {
                    if (r.Age >= 18 && r.Age <= 24)
                        return "18-24岁";
                    if (r.Age >= 25 && r.Age <= 29)
                        return "25-29岁";
                    if (r.Age >= 30 && r.Age <= 39)
                        return "30-39岁";
                    if (r.Age >= 40 && r.Age <= 49)
                        return "40-49岁";
                    return "50岁以上";
                })
                .Select(g => new AgeGroupDto
                {
                    AgeGroup = g.Key,
                    Count = g.Count()
                })
                .ToList();
            return ageGroups;
        }

        /// <summary>
        /// 获取员工工龄比
        /// </summary>
        /// <param name="comamnd"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<WorkExperienceGroupDto>> WorkExperienceGroupAsync([FromQuery]AgeGroupCommand comamnd)
        {
            var currentDate = DateTime.Now;  // 当前日期
            var gather = await mediator.Send(comamnd);
            gather = gather.Where(x => x.State == "试用期" || x.State == "待转正" || x.State == "已转正" || x.State == "待离职").ToList();
            // 查询并生成按工作年限分组的统计信息
            var workExperienceGroups = gather
                .Select(r => new
                {
                    // 计算工作年限
                    WorkYears = r.Hiredate.HasValue
                        ? (int)((currentDate - r.Hiredate.Value).TotalDays / 365.25)  // 按照年计算工作年限
                        : 1,  // 如果 Hiredate 是 null，则默认工作年限为 0
                    r.Id
                })
                .GroupBy(r =>
                {
                    // 按工作年限区间分组
                    if (r.WorkYears >= 0 && r.WorkYears <= 3)
                        return "1-3年";
                    if (r.WorkYears >= 4 && r.WorkYears <= 6)
                        return "4-6年";
                    if (r.WorkYears >= 7 && r.WorkYears <= 9)
                        return "7-9年";
                    return "10年以上";
                })
                .Select(g => new WorkExperienceGroupDto  // 返回 WorkExperienceGroupDto 类型
                {
                    name = g.Key,
                    value = g.Count()
                })
                .ToList();  // 转换为 List<WorkExperienceGroupDto>

            return workExperienceGroups;
        }

        /// <summary>
        /// 获取部门人数
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<DepartmentCountsDto>> DepartmentCountsAsync([FromQuery]AgeGroupCommand command)
        {
            var gather = await mediator.Send(command);
            gather = gather.Where(x => x.State == "试用期" || x.State == "待转正" || x.State == "已转正" || x.State == "待离职").ToList();
            // 查询每个部门的员工数量
            var departmentCounts = gather
                .GroupBy(r => r.Department)  // 按部门分组
                .Select(g => new DepartmentCountsDto
                {
                    name = g.Key,        // 部门名称
                    value = g.Count()  // 该部门员工的数量
                }).ToList(); // 执行查询，返回结果列表
            return departmentCounts;
        }

        /// <summary>
        /// 获取员工总人数
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<int> GetCountAsync([FromQuery] AgeGroupCommand command)
        {
            var gather = await mediator.Send(command);
            gather = gather.Where(x=>x.State=="试用期"||x.State=="待转正"||x.State=="已转正"||x.State=="待离职").ToList();
            return gather.Count();
        }
    }
}
